<template>
  <div class="container">
    <div class="sign-in">
      <!-- 注册 -->
      <div class="loginLogo"
           @click="routerHome">
        <div class="colorS">小囧科技</div>
      </div>
      <div class="loginFrom">
        <el-form class="form login-form clear-fix"
                 ref="RegFormRef"
                 status-icon
                 hide-required-asterisk
                 :model="registerForm"
                 :rules="loginRules">
          <el-form-item label="手机号码"
                        prop="mobile"
                        required="true">
            <el-input v-model="registerForm.mobile"
                      placeholder="请输入手机号码"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码"
                        prop="pass"
                        required="true">
            <el-input v-model="registerForm.pass"
                      type="password"
                      placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名"
                        prop="userName">
            <el-input v-model="registerForm.userName"
                      placeholder="请输入姓名"
                      autocomplete="off"
                      required="true"></el-input>
          </el-form-item>
          <el-form-item label="邀&nbsp;&nbsp;请&nbsp;&nbsp;码"
                        prop="visitCode">
            <el-input v-model="registerForm.visitCode"
                      placeholder="请输入邀请码"
                      autocomplete="off"></el-input>
          </el-form-item>
          <!-- 验证码 -->
          <el-form-item prop="verification"
                        class="iptBox verification_box"
                        required="true">
            <i class="iconfont icon-dunpai"></i>
            <el-input class="iptphone yzmcation"
                      v-model="registerForm.verification"
                      placeholder="请输入验证码"
                      maxlength="6"></el-input>
            <div class="fasonyzmBox">
              <span @click="registersendCode"
                    class="fasonyzmtext"
                    v-if="codeShow">验证码
              </span>
              <span @click="registersendCode"
                    class="fasonyzmtext"
                    v-if="!codeShow">{{count+'s'}}</span>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="submitBtn">
              <el-button type="danger"
                         @keyup.enter.native="submitForm()"
                         class="form-btn submit-btn"
                         @click="submitForm()"
                         :loading="loadingButton">
                {{loadingButtonText}}
              </el-button>
              <el-button class="form-btn reset-btn"
                         @click="resetForm()"> 重置</el-button>
            </div>
          </el-form-item>
          <div class="toLogin"
               @click="toLogin">
            <span>已有账号,请登录</span>
          </div>
        </el-form>
      </div>

    </div>
    <div class="sign-up"></div>
  </div>
</template>

<script>
import { ref, reactive, unref, toRefs, onUnmounted, onBeforeUnmount, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getPhoneCode, vitiedCodeRegister } from '@/network/login'
import { ElMessage } from "element-plus";
// import { setLocal } from '@/utils/cookie'
// import md5 from 'js-md5'
// import { ElLoading } from 'element-plus'
// 对密码和邮箱进行类型限制
export default ({
  setup () {
    const router = useRouter();
    const RegFormRef = ref(null);
    const state = reactive({
      loadingButtonText: '注册',
      loadingButton: false,
      count: '',
      codeShow: true,
      timer: null,//时间
      registerForm: {
        mobile: "",
        pass: "",
        userName: "",
        visitCode: '',//邀请码
        verification: '',//验证码
      },
    })
    // // 手机验证
    const validatePhone = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (!reg.test(value)) {
        callback(new Error('手机号码格式有误'))
      } else {
        callback()
      }
    }
    // 密码验证
    const validatePass = (rule, value, callback) => {
      //  密码只能由大小写英文字母或数字开头，且由大小写英文字母_.组成
      const reg = /^[A-Za-z0-9][A-Za-z0-9_.]{5,14}$/;
      if (!reg.test(value)) {
        callback(
          new Error("密码由字母或数字开头，且只能为字母,数字,下划线及（.）")
        );
      } else {
        callback();
      }
    }

    const loginRules = reactive({
      mobile: [
        { required: true, message: "手机号码不能为空", trigger: "blur" },
        { validator: validatePhone, trigger: "blur" },
      ],
      pass: [
        { required: true, message: "密码不能为空", trigger: "blur" },
        { min: 6, max: 15, message: "密码位数只能在6~15之间", trigger: "blur" },
        { validator: validatePass, trigger: "blur" },
      ],
      userName: [
        {
          required: true, message: '姓名不能为空', trigger: 'blur'
        }
      ],
      verification: [
        { required: true, message: '验证码不能为空', trigger: 'blur' }
      ]
    })
    // 重置表单
    const resetForm = () => {
      const form = unref(RegFormRef);
      form.resetFields();
    }

    // 验证码发送
    const registersendCode = () => {
      if (!state.registerForm.mobile) {
        ElMessage({
          message: '手机号码为空',
          type: 'error',
          duration: 1000
        })
      } else {
        getPhoneCode({
          mobile: state.registerForm.mobile,
        }).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: '验证码发送成功',
              type: 'success',
              duration: 1000
            })
            setTimeout(() => {
              ElMessage.closeAll()
            }, 1000)
            if (!state.timer) {
              const timeCount = 60
              state.count = timeCount
              state.codeShow = false
              state.timer = setInterval(() => {
                if (state.count > 0 && state.count <= timeCount) {
                  state.count--
                } else {
                  state.codeShow = true
                  clearInterval(state.timer)
                  state.timer = null
                }
              }, 1000)
            }
          } else {
            ElMessage.error(`${res.message}`)
            setTimeout(() => {
              ElMessage.closeAll()
            }, 1000)
          }
        })
      }
    }
    // 表单提交
    const submitForm = () => {
      RegFormRef.value.validate(async (valid) => {
        if (valid) {
          state.loadingButton = true
          state.loadingButtonText = '注册中...'
          await vitiedCodeRegister({
            mobile: state.registerForm.mobile,
            vcode: state.registerForm.verification,
            name: state.registerForm.userName,
            password: state.registerForm.pass,
            invitationCode: state.registerForm.visitCode,
            registerAuditType: 2,
          }).then((res => {
            if (res.code == 200) {
              ElMessage({
                message: '注册成功',
                type: 'success',
                duration: 1000
              })
              state.loadingButton = false
              state.loadingButtonText = '注册'
              router.push({
                path: '/login',
                query: {
                  mobile: encodeURI(state.registerForm.mobile),
                }
              })
            } else {
              ElMessage.error(`${res.message}`)
              state.loadingButton = false
              state.loadingButtonText = '注册'
            }
          }))
        }
      })
    };
    // 
    const toLogin = () => {
      router.push('/login')
    }
    onMounted(() => {
      document.onkeydown = (e) => {
        if (e.keyCode == 13 || e.key == 'enter') {
          submitForm()
        }
      }
    })
    const routerHome = () => {
      router.push('/')
    }
    // 生命周期销毁定时器
    onUnmounted(() => {
      clearInterval(state.timer);
      state.timer = null;
    });
    onBeforeUnmount(() => {
      clearInterval(state.timer);
      state.timer = null;
    });
    return {
      ...toRefs(state),
      RegFormRef,
      resetForm,
      submitForm,
      loginRules,
      registersendCode,
      toLogin,
      routerHome
    };
  },
});
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
.sign-in {
  background: url("../../assets/images/loginbg.png") no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
  position: relative;
  .loginLogo {
    display: flex;
    justify-content: center;
    padding-top: 80px;
    .colorS {
      font-size: 26px;
      color: #fff;
    }
  }
}
.loginFrom {
  width: 800px;
  padding: 30px 40px;
  border-radius: 10px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  .el-form {
    border-radius: 8px;
  }
}
.tiparea {
  float: right;
  a {
    color: blue;
    &:hover {
      color: red;
      cursor: pointer;
    }
  }
}
.login-form {
  box-shadow: 5px 5px 5px 5px darken(#ccc, 0.1);
  padding: 30px;
}
.form-btn {
  width: 48%;
}
.reset-btn {
  float: right;
}
.el-form {
}
.iptBox {
  .fasonyzmBox {
    padding: 0 5px;
    background-color: transparent;
    position: absolute;
    right: 0;
    top: 20px;
    border: none;
    width: 90px;
    border-left: 1px solid hsla(0, 0%, 100%, 0.1);
    line-height: 20px;

    .fasonyzmtext {
      color: #666;
      font-size: 14px;
      cursor: pointer;
      display: flex;
      justify-content: center;
      text-align: center;
      &:hover {
        -webkit-filter: brightness(1.1);
        filter: brightness(1.1);
      }

      &:active {
        -webkit-filter: brightness(0.95);
        filter: brightness(0.95);
      }
    }
  }
}
// 发送验证码样式
.verification_box {
  /deep/.el-form-item__content {
    margin-left: 72px;
    display: flex;
    align-items: center;
    .yzmcation {
      flex: 8;
      .el-input__inner {
        padding-right: 0px;
      }
    }

    .fasonyzmBox {
      user-select: none;
      flex: 1;
      line-height: 40px;
      margin: 10px 0;
      position: static;
      background: #248fff;
      margin-left: 10px;
      border-radius: 4px;

      &:hover {
        background: linear-gradient(135deg, #4ac2ff 100%, #248fff 0%);
      }

      .fasonyzmtext {
        color: #fff;
      }
    }

    .forbidden {
      background: #999;
      pointer-events: none !important;
    }
  }
}
.submitBtn {
  display: flex;
  justify-content: flex-end;
  /deep/.form-btn {
    width: 25%;
  }
}
.toLogin {
  cursor: pointer;
  display: flex;
  justify-content: flex-end;
  font-size: 14px;
  color: #666;
}
</style>